from flask import render_template, current_app, session, jsonify, request

from info.models import *
from info.utlis.response_code import *

from . import index_blu


# 左边新闻
@index_blu.route("/news_list")
def news_list():
    """
    获取，查询并返回
    :return:
    """

    # 获取参数  cid page
    cid = request.args.get('cid','1')
    page = request.args.get('page','1')
    per_page = request.args.get('per_page','10')

    # 检验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 如果cid为1  则直接顺序查询
    filter_list = []

    if not cid == 1:
        filter_list.append(News.category_id == cid)

    print(filter_list)

    try:
        paginate = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    print(paginate)

    # 取到查询信息分页信息及页数 new_model_list,total_page,current_page
    new_model_list = paginate.items   #  返回一个对象模型，需要调用方法
    total_page = paginate.pages # 返回一页的数据
    current_page = paginate.page # 返回页数
    print(new_model_list)

    new_dict_li = []
    for news in new_model_list:
        new_dict_li.append(news.to_basic_dict())

    print(new_dict_li)
    date = {
        'total_page': total_page,
        'current_page': current_page,
        'new_dict': new_dict_li
    }

    return jsonify(errno=RET.OK, errmsg="请求成功", data=date)






# 右上角登陆显示
@index_blu.route('/')
def index():
    # 右上角登陆显示
   # 取到当前的session
    user_id = session.get('user_id')
    user = None
    if user_id:
       try:
           user = User.query.get(user_id)
       except  Exception as e:
           current_app.logger.error(e)


    # 右侧实现新闻排行
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DATAERR, errmsg='4004')

    news_click_list = []

    for new in news_list if news_list else []:
        news_click_list.append(new.to_basic_dict())

    # 新闻分类
    categories = Category.query.all()

    categories_list = []
    for category in categories:
        categories_list.append(category.to_dict())




    date = {
        "user_id":user.to_dict()if user else None,
        "news_id":news_click_list,
        'news_class':categories_list
        }



    return render_template('news/index.html',date =date)

@index_blu.route('/favicon.ico')
def favicon():

    return current_app.send_static_file('news/favicon.ico')


